﻿/*
 * 描述：     DoubleClickButton
 */
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DoubleClickButton : Button
{
    [Serializable]
    public class DoubleClickedEvent : UnityEvent { }

    [SerializeField]
    private DoubleClickedEvent _onDoubleClick = new DoubleClickedEvent();

    public DoubleClickedEvent onDoubleClick
    {
        get { return _onDoubleClick; }
        set { _onDoubleClick = value; }
    }

    private DateTime _firstTime;
    private DateTime _secondTime;

    private void Press()
    {
        if (onDoubleClick != null) { onDoubleClick.Invoke(); }
        ResetTime();
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        if (_firstTime.Equals(default(DateTime))) { _firstTime = DateTime.Now; }
        else { _secondTime = DateTime.Now; }
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        if (!_firstTime.Equals(default(DateTime)) && !_secondTime.Equals(default(DateTime)))
        {
            var intervalTime = _secondTime - _firstTime;
            float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
            if (milliSeconds < 400) { Press(); }
            else { ResetTime(); }
        }
    }

    public override void OnPointerExit(PointerEventData eventData)
    {
        base.OnPointerExit(eventData);
        ResetTime();
    }

    private void ResetTime()
    {
        _firstTime = default(DateTime);
        _secondTime = default(DateTime);
    }
}
